package com.example.zhangjingyu

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.example.zhangjingyu.R

class WordAdapter(private val wordList: MutableList<Word>, private val onDeleteClickListener: OnDeleteClickListener) : RecyclerView.Adapter<WordAdapter.WordViewHolder>() {

    interface OnDeleteClickListener {
        fun onDeleteClick(word: Word)
    }

    class WordViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView), View.OnLongClickListener {
        val wordTextView: TextView = itemView.findViewById(R.id.wordTextView)
        private var onDeleteClickListener: OnDeleteClickListener? = null
        private var word: Word? = null

        init {
            itemView.setOnLongClickListener(this)
        }

        fun bind(word: Word, onDeleteClickListener: OnDeleteClickListener) {
            this.word = word
            this.onDeleteClickListener = onDeleteClickListener
            wordTextView.text = word.text
        }

        override fun onLongClick(v: View?): Boolean {
            word?.let { onDeleteClickListener?.onDeleteClick(it) }
            return true
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): WordViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.word_item, parent, false)
        return WordViewHolder(view)
    }

    override fun onBindViewHolder(holder: WordViewHolder, position: Int) {
        holder.bind(wordList[position], onDeleteClickListener)
    }

    override fun getItemCount() = wordList.size
}